# -*- coding: utf-8 -*-
"""
Created on Thu Jul  7 17:21:34 2022

@author: lenovo
"""



import global_var
import os


def plottree(mdic,onode):
   for key in mdic.keys():
       mdic[key].append(0)
       #print(mdic)
    

   list1=[]  #上级节点的记录
   list2=[]  #已经完成dic的记录
   def func(node):
       a = mdic[node][-1] #此节点已完成次数
       #print(a)
       if len(mdic[node]) == 1: 
          ndic={}
          ndic['name']=node
          list2.append(ndic)
          mdic[node][-1]=a+1
          mdic[list1[-1]][-1]+=1
          return func(list1[-1])
       else:
          try:
            
             if a < len(mdic[node])-1:
                list1.append(node)
                return func(mdic[node][a])
             elif a == len(mdic[node])-1:
                pdic={}
                pdic['name']=node
                list3=[]
                for enode in mdic[node][0:-1]:
                   for edic in list2:
                      if edic['name'] == enode:
                         #print(edic)
                         list3.append(edic)
                         #print(list3)
                         break
                pdic['children']=list3
                #print(pdic)
                list2.append(pdic)
                list1.append(node)
                for key in mdic.keys():
                   if node in mdic[key]:
                      mnode = key
                      break
                mdic[mnode][-1] += 1
                #print(node)
                return (func(mnode))
          except:
             return pdic
             
             
    #func(onode)
    #print(list1)
    #print(list2)
   #print(func(onode))
   #import json
   #import os

   from pyecharts import options as opts
   from pyecharts.charts import Tree

   data=[func(onode)]
   tree=(
       Tree()
          .add("", data)
          .set_global_opts(title_opts=opts.TitleOpts(title="Tree"))
       )

   tree.render(path= global_var.get_value('direction') + 'files_generated' + os.sep + 'plot.html')
   


#mdic = {'1': ['3'], '10': ['13'], '100': ['1', '2'], '12': [], '13': [], '15': [], '16': [], '2': ['4'], '24': ['31', '32'], '25': [], '26': [], '27': ['10'], '3': ['5', '6', '9', '26', '50'], '31': [], '32': [], '4': ['8', '15', '24', '16', '27'], '5': [], '50': [], '6': [], '8': [], '9': ['12', '25']}
#onode = '100'
#plottree(mdic,onode)